import 'package:dio/dio.dart';
import 'package:flutter_demo/entities/article_item.dart';
import 'package:flutter_demo/entities/category.dart';
import 'package:flutter_demo/utils/dom_parser.dart';
import 'package:get/get.dart';

import '../views/loading_container.dart';

class CategoryListController extends GetxController {
  static const categories = <List<CategoryTab>>[
    [
      CategoryTab("switchyouxi", "所有"),
      CategoryTab("buding-dlc", "更新"),
      CategoryTab("3ajuzuo", "3A巨作"),
      CategoryTab("jinshouzhi", "加藤之指"),
      CategoryTab("gj", "工具"),
      CategoryTab("zhuti", "主题"),
    ],
    [
      CategoryTab("pcgame", "所有"),
      CategoryTab("pcsmall", "小仓库"),
    ],
    [
      CategoryTab("zhangji", "所有"),
    ],
    [
      CategoryTab("ting", "听我"),
      CategoryTab("pijiu", "周边"),
    ],
  ];

  final int index;
  List<CategoryTab> tabs = List<CategoryTab>.empty();

  final list = List<ArticleItem>.empty(growable: true).obs;
  final selectTab = 0.obs;
  final listLoadingStatus = LoadStatus.loading.obs;
  final hasMore = true.obs;
  final selectType = "all".obs;
  final selectSort = "date".obs;

  var page = 1;

  CategoryListController(this.index) {
    tabs = categories[index];
  }

  @override
  void onReady() {
    super.onReady();
    changeTab(0);
  }

  setSelectType(String selectType) {
    this.selectType.value = selectType;
    getList();
  }

  setSelectSort(String selectSort) {
    this.selectSort.value = selectSort;
    getList();
  }

  changeTab(int index) {
    selectTab.value = index;
    list.clear();
    getList();
  }

  getList({init = true}) async {
    if (list.isNotEmpty) {
      listLoadingStatus.value = LoadStatus.success;
    } else {
      listLoadingStatus.value = LoadStatus.loading;
    }
    var requestPage = page;
    if (!init) {
      requestPage++;
    }
    final currentTab = tabs[selectTab.value];
    try {
      final response = await Dio()
          .get<String>("https://fourpetal.com/${currentTab.value}/page/$requestPage?order=$selectSort&cao_type=$selectType");
      final result = DomParser.parseArtilceList(response.data);
      hasMore.value = result.length >= 15;
      page = requestPage;
      if (init) {
        list.clear();
      }
      list.addAll(result);
    } catch (_) {
    }
    if (list.isEmpty) {
      listLoadingStatus.value = LoadStatus.empty;
    } else {
      listLoadingStatus.value = LoadStatus.success;
    }
  }
}
